package com.zhentao.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zhentao.Exception.vo.ResultVo;
import com.zhentao.config.ExcelImportService;
import com.zhentao.pojo.Brand;
import com.zhentao.pojo.Category;
import com.zhentao.pojo.Product;
import com.zhentao.service.BrandService;
import com.zhentao.service.CategoryService;
import com.zhentao.ResponseResult;
import com.zhentao.TextModerationPlusUtil;
import com.zhentao.service.FileStorageService;
import com.zhentao.service.ProductService;
import lombok.SneakyThrows;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.util.StringUtils;
import org.springframework.context.annotation.Bean;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import com.baomidou.mybatisplus.annotation.DbType;
import org.springframework.context.annotation.Configuration;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


import java.io.File;
import java.io.FileOutputStream;
import java.util.Date;
import java.util.List;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("product")
public class ProductController {
    private static final Logger log = LoggerFactory.getLogger(ProductController.class);
    @Autowired
    private ProductService productService;
    @Autowired
    private CategoryService categoryService;
    @Autowired
    private BrandService brandService;
    @Autowired
    private FileStorageService fileStorageService;

    /**
     * 获取所有分类（用于下拉菜单）
     */
    @GetMapping("/categories")
    public ResultVo getAllCategories() {
        List<Category> categories = categoryService.list();
        return ResultVo.success(categories);
    }

    /**
     * 获取所有品牌（用于下拉菜单）
     */
    @GetMapping("/brands")
    public ResultVo getAllBrands() {
        List<Brand> brands = brandService.list();
        return ResultVo.success(brands);
    }
    //用户模糊查询
    @GetMapping("/list2")
    public ResultVo listProduct(
            @RequestParam(required = false) Long categoryId,
            @RequestParam(required = false) Long brandId,
            @RequestParam(required = false) String keyword) {
        try {
            // 创建查询条件构造器
            LambdaQueryWrapper<Product> wrapper = new LambdaQueryWrapper<>();
            
            // 设置基础条件
            wrapper.eq(Product::getIsDeleted, 1)
                   .eq(Product::getStatus, 1); // 假设1表示上架状态
            
            // 动态添加查询条件
            // 使用Lambda表达式，避免字段名写错
            wrapper.eq(categoryId != null, Product::getCategoryId, categoryId)
                   .eq(brandId != null, Product::getBrandId, brandId)
                   .like(StringUtils.hasText(keyword), Product::getName, keyword);
            
            // 添加排序
            wrapper.orderByDesc(Product::getCreateTime);
            
            // 执行查询
            List<Product> products = productService.list(wrapper);
            
            // 补充品牌和分类信息
            for (Product product : products) {
                // 获取品牌信息
                Brand brand = brandService.getById(product.getBrandId());
                if (brand != null) {
                    product.setBrandName(brand.getName());
                } else {
                    product.setBrandName("未知品牌");
                }
                
                // 获取分类信息
                Category category = categoryService.getById(product.getCategoryId());
                if (category != null) {
                    product.setCategoryName(category.getName());
                } else {
                    product.setCategoryName("未知分类");
                }
            }
            
            // 记录日志
            log.info("查询条件：categoryId={}, brandId={}, keyword={}", categoryId, brandId, keyword);
            log.info("查询结果数量：{}", products.size());
            
            return ResultVo.success(products);
            
        } catch (Exception e) {
            log.error("查询商品列表失败", e);
            return ResultVo.error(500, "获取商品列表失败：" + e.getMessage());
        }
    }

    /**
     * 查询商品列表（分页，支持按分类和品牌筛选）
     */
    @GetMapping("/list")
    public ResultVo list(
            @RequestParam(value = "page", defaultValue = "1", required = false) Integer page,
            @RequestParam(value = "size", defaultValue = "5", required = false) Integer size,
            @RequestParam(value = "categoryId", required = false) Long categoryId,
            @RequestParam(value = "brandId", required = false) Long brandId,
            @RequestParam(value = "keyword", required = false) String keyword) {

        try {
            // 调试日志，确认参数接收情况
            System.out.println("接收的分页参数 - page: " + page + ", size: " + size);

            // 参数校验和默认值设置
            if (page == null || page < 1) page = 1;
            if (size == null || size < 1) size = 5;
            if (size > 100) size = 100;  // 限制最大页面大小

            // 创建分页对象
            Page<Product> pageParam = new Page<>(page, size);

            // 构建查询条件
            LambdaQueryWrapper<Product> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(Product::getIsDeleted, 1); // 假设未删除是0，根据实际情况调整

            // 添加查询条件（如果有）
            if (categoryId != null) {
                queryWrapper.eq(Product::getCategoryId, categoryId);
            }
            if (brandId != null) {
                queryWrapper.eq(Product::getBrandId, brandId);
            }
            if (StringUtils.hasText(keyword)) {
                queryWrapper.like(Product::getName, keyword);
            }

            // 按创建时间降序排序
            queryWrapper.orderByDesc(Product::getCreateTime);

            // 执行分页查询
            Page<Product> pageResult = productService.page(pageParam, queryWrapper);

            // 如果当前页大于最大页数，则重新查询第一页
            if (pageResult.getCurrent() > pageResult.getPages() && pageResult.getPages() > 0) {
                pageParam.setCurrent(1);
                pageResult = productService.page(pageParam, queryWrapper);
            }

            // 获取分页数据
            List<Product> records = pageResult.getRecords();

            // 补充品牌和分类信息
            for (Product product : records) {
                // 获取品牌信息
                Brand brand = brandService.getById(product.getBrandId());
                if (brand != null) {
                    product.setBrandName(brand.getName());
                } else {
                    product.setBrandName("未知品牌");
                }

                // 获取分类信息
                Category category = categoryService.getById(product.getCategoryId());
                if (category != null) {
                    product.setCategoryName(category.getName());
                } else {
                    product.setCategoryName("未知分类");
                }
            }

            // 更新分页结果的记录
            pageResult.setRecords(records);

            // 打印分页信息，用于调试
            System.out.println("分页信息：当前页=" + pageResult.getCurrent()
                    + ", 每页大小=" + pageResult.getSize()
                    + ", 总记录数=" + pageResult.getTotal()
                    + ", 总页数=" + pageResult.getPages()
                    + ", 本页记录数=" + pageResult.getRecords().size());

            // 添加详细日志
            log.info("查询条件：categoryId={}, brandId={}, keyword={}", categoryId, brandId, keyword);
            log.info("总数据量：{}", pageResult.getTotal());
            log.info("当前页数据：{}", pageResult.getRecords().size());
            log.info("是否有下一页：{}", pageResult.hasNext());

            // 直接返回Page对象，保持MyBatis-Plus的分页结构
            return ResultVo.success(pageResult);

        } catch (Exception e) {
            log.error("查询失败", e);
            return ResultVo.error(500, "获取商品列表失败：" + e.getMessage());
        }
    }

    /**
     * 添加商品
     */
    @PostMapping("/add")
    @SneakyThrows
    public ResultVo add(@RequestParam("file") MultipartFile file,@ModelAttribute Product product) {
        // 验证品牌和分类是否存在
        Brand brand = brandService.getById(product.getBrandId());
        Category category = categoryService.getById(product.getCategoryId());

        if (brand == null || brand.getIsDeleted() == 0) {
            return ResultVo.error(400, "所选品牌不存在或已被禁用");
        }
        if (category == null || category.getStatus() == 0 || category.getIsDeleted() == 0) {
            return ResultVo.error(400, "所选分类不存在或不可用");
        }
        // 内容审核
        ResponseResult moderationResult = TextModerationPlusUtil.checkContent(product.getName());
        if (moderationResult.getCode() != 600) {
            return ResultVo.error(601, "商品名称审核未通过");
        }

        product.setImage(fileStorageService.uploadImgFile(file.getOriginalFilename(), file.getInputStream()));
        product.setSaleNum(0);
        product.setCreateTime(new Date());
        product.setStatus(1);// 1:上架 0:下架
        product.setIsDeleted(1); // 1表示可用

        return productService.save(product) ? ResultVo.success() : ResultVo.error();
    }

    /**
     * 根据ID查询商品（包含品牌和分类信息）
     */
    @GetMapping("/getById/{id}")
    public ResultVo getById(@PathVariable Long id) {
        Product product = productService.getById(id);
        if (product == null) {
            return ResultVo.error();
        }

        // 补充品牌和分类信息
        Brand brand = brandService.getById(product.getBrandId());
        Category category = categoryService.getById(product.getCategoryId());

        Map<String, Object> result = new HashMap<>();
        result.put("product", product);
        result.put("brand", brand);
        result.put("category", category);

        return ResultVo.success(result);
    }

    /**
     * 修改商品
     */
    @PostMapping("/update")
    @SneakyThrows
    public ResultVo update(@RequestParam("file") MultipartFile file,@ModelAttribute Product product) {
        Product byId = productService.getById(product.getId());
        if (byId == null) {
            return ResultVo.error();
        } else {
            // 验证品牌和分类是否存在
            if (product.getBrandId() != null && product.getCategoryId() != null && product.getName() != null) {
                Brand brand = brandService.getById(product.getBrandId());
                Category category = categoryService.getById(product.getCategoryId());


                if (brand.getIsDeleted() == 0) {
                    return ResultVo.error(400, "所选品牌不存在或已被禁用");
                }
                if (category.getStatus() == 0 || category.getIsDeleted() == 0) {
                    return ResultVo.error(400, "所选分类不存在或不可用");
                }

                ResponseResult moderationResult = TextModerationPlusUtil.checkContent(product.getName());
                if (moderationResult.getCode() != 600) {
                    return ResultVo.error(601, "商品名称审核未通过");
                }
                product.setImage(fileStorageService.uploadImgFile(file.getOriginalFilename(), file.getInputStream()));
                product.setUpdateTime(new Date());
              product.setStatus(product.getStatus());// 1:上架 0:下架
            product.setIsDeleted(product.getIsDeleted()); // 1表示可用
            }
            return productService.updateById(product) ? ResultVo.success() : ResultVo.error(500, "修改失败");
        }
    }

    /**
     * 删除商品
     */
    @DeleteMapping("/delete/{id}")
    public ResultVo delete(@PathVariable Long id) {
        return productService.removeById(id) ? ResultVo.success() : ResultVo.error();
    }

    /**
     * 商品上下架
     */
    @PutMapping("/updateStatus/{id}/{status}")
    public ResultVo updateStatus(@PathVariable Long id, @PathVariable Integer status) {
        Product product = new Product();
        product.setId(id);
        product.setStatus(status); // 0:下架 1:上架
        product.setUpdateTime(new Date());
        return productService.updateById(product) ? ResultVo.success() : ResultVo.error();
    }
    @GetMapping("/exportExcel")
    @SneakyThrows
    public void exportExcel(){
        // 准备数据
        List<Product> data = productService.list();
        // 创建工作簿和工作表
        try (Workbook workbook = new XSSFWorkbook()) {
            Sheet sheet = workbook.createSheet("产品列表");

            // 创建日期格式样式
            CellStyle dateStyle = workbook.createCellStyle();
            CreationHelper creationHelper = workbook.getCreationHelper();
            dateStyle.setDataFormat(creationHelper.createDataFormat().getFormat("yyyy-MM-dd HH:mm:ss"));
            // 创建表头
            Row headerRow = sheet.createRow(0);
            String[] headers = {"ID", "产品名称","品牌","分类", "价格", "库存", "销量","商品描述","创建时间"};
            for (int i = 0; i < headers.length; i++) {
                Cell cell = headerRow.createCell(i);
                cell.setCellValue(headers[i]);
            }
            // 填充数据
            for (int i = 0; i < data.size(); i++) {
                Product product = data.get(i);
                Row row = sheet.createRow(i + 1);
                row.createCell(0).setCellValue(product.getId());
                row.createCell(1).setCellValue(product.getName());
                row.createCell(2).setCellValue(brandService.getById(product.getBrandId()).getName());
                row.createCell(3).setCellValue(categoryService.getById(product.getCategoryId()).getName());
                row.createCell(4).setCellValue(product.getPrice());
                row.createCell(5).setCellValue(product.getStock());
                row.createCell(6).setCellValue(product.getSaleNum());
                row.createCell(7).setCellValue(product.getDescription());
                // 处理日期格式
                Cell dateCell = row.createCell(8);
                dateCell.setCellValue(product.getCreateTime());
                dateCell.setCellStyle(dateStyle);

            }
            // 自动调整列宽
            for (int i = 0; i < headers.length; i++) {
                sheet.autoSizeColumn(i);
            }
            // 设置导出路径，这里以Windows路径为例，可根据实际情况修改
            String exportPath = "D:/excel_export/";
            File folder = new File(exportPath);
            if (!folder.exists()) {
                folder.mkdirs();
            }
            String fileName = "产品数据.xlsx";
            try (FileOutputStream fileOut = new FileOutputStream(exportPath + fileName)) {
                workbook.write(fileOut);
            }
        }
    }
    @Autowired
    private ExcelImportService importService;

    @PostMapping("/import")
    public String importExcel(@RequestParam("file") MultipartFile file) {
        try {
            importService.importExcel(file.getInputStream());
            return "导入成功";
        } catch (Exception e) {
            e.printStackTrace();
            return "导入失败: " + e.getMessage();
        }
    }

    /**
     * 根据商品名称模糊查询
     * @param name 商品名称关键词
     * @return 匹配的商品列表
     */
    @GetMapping("/searchByName")
    public ResultVo searchByName(@RequestParam String name) {
        if (!StringUtils.hasText(name)) {
            return ResultVo.error(400, "搜索关键词不能为空");
        }

        LambdaQueryWrapper<Product> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(Product::getName, name)
                   .eq(Product::getIsDeleted, 1)  // 只查询未删除的商品
                   .orderByDesc(Product::getCreateTime);  // 按创建时间降序

        List<Product> products = productService.list(queryWrapper);

        // 补充品牌和分类信息
        products.forEach(product -> {
            Brand brand = brandService.getById(product.getBrandId());
            Category category = categoryService.getById(product.getCategoryId());
            if (brand != null) {
                product.setBrandName(brand.getName());
            }
            if (category != null) {
                product.setCategoryName(category.getName());
            }
        });

        return ResultVo.success(products);
    }

    @GetMapping("/test-page")
    public ResultVo testPage() {
        // 创建分页对象，第一页，5条数据
        Page<Product> page = new Page<>(1, 5);
        // 查询总数据量
        LambdaQueryWrapper<Product> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Product::getIsDeleted, 0);
        long total = productService.count(wrapper);
        System.out.println("总数据量：" + total);

        // 执行分页查询
        Page<Product> result = productService.page(page, wrapper);
        System.out.println("当前页数据量：" + result.getRecords().size());
        System.out.println("总页数：" + result.getPages());

        return ResultVo.success(result);
    }
    /**
     * 批量查询商品信息
     * @param ids 商品ID列表
     * @return 商品信息列表
     */
    @PostMapping("/batchQuery")
    public ResultVo batchQuery(@RequestBody List<Long> ids) {
        try {
            if (ids == null || ids.isEmpty()) {
                return ResultVo.error(400, "商品ID列表不能为空");
            }

            // 创建查询条件
            LambdaQueryWrapper<Product> wrapper = new LambdaQueryWrapper<>();
            wrapper.in(Product::getId, ids)
                    .eq(Product::getIsDeleted, 1)  // 1表示可用
                    .eq(Product::getStatus, 1);    // 1表示上架状态

            // 执行查询
            List<Product> products = productService.list(wrapper);

            // 补充品牌和分类信息
            for (Product product : products) {
                // 获取品牌信息
                Brand brand = brandService.getById(product.getBrandId());
                if (brand != null) {
                    product.setBrandName(brand.getName());
                } else {
                    product.setBrandName("未知品牌");
                }

                // 获取分类信息
                Category category = categoryService.getById(product.getCategoryId());
                if (category != null) {
                    product.setCategoryName(category.getName());
                } else {
                    product.setCategoryName("未知分类");
                }
            }

            // 记录日志
            log.info("批量查询商品，ID列表：{}", ids);
            log.info("查询结果数量：{}", products.size());

            // 如果有未找到的商品ID，记录下来
            List<Long> foundIds = products.stream()
                    .map(Product::getId)
                    .collect(java.util.stream.Collectors.toList());
            List<Long> notFoundIds = ids.stream()
                    .filter(id -> !foundIds.contains(id))
                    .collect(java.util.stream.Collectors.toList());

            if (!notFoundIds.isEmpty()) {
                log.warn("以下商品ID未找到：{}", notFoundIds);
            }

            Map<String, Object> result = new HashMap<>();
            result.put("products", products);
            result.put("total", products.size());
            result.put("notFoundIds", notFoundIds);

            return ResultVo.success(result);

        } catch (Exception e) {
            log.error("批量查询商品失败", e);
            return ResultVo.error(500, "批量查询商品失败：" + e.getMessage());
        }
    }
}



